package com.cj.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cj.model.Bonus;
import com.cj.model.Employee;
import com.cj.model.common.BonusType;
import com.cj.utils.StrUtil;
import com.jfinal.core.Controller;

public class BonusController extends Controller {
	
	public void index() {
		Employee employee = (Employee)getSession().getAttribute("employee");
		Integer empId = employee.getInt("empId");
		Integer isAdmin = employee.getInt("isAdmin");
		List<Employee> employees = Employee.me.getAllEmployees();
		List<String> bonusTypes = new ArrayList<String>();
		List<Bonus> bonusList = null;
		for (BonusType b : BonusType.values()) {
			bonusTypes.add(b.getName());
		}
		if(isAdmin == 1) {
			bonusList = Bonus.me.getAllBonus();
		} else {
			bonusList = Bonus.me.getBonusByEmployee(empId);
		}
		setAttr("employees", employees);
		setAttr("bonusTypes", bonusTypes);
		setAttr("bonusList", bonusList);
		render("bonus.jsp");
	}
	
	public void add() {
		Bonus bonus = getModel(Bonus.class);
		setBonusTime(bonus);
		String[] empIds = getParaValues("bonus.empId");
		setBonusTime(bonus);
		for (String empId : empIds) {
			if(StrUtil.notBlank(empId)) {
				bonus.remove("bonusId");
				bonus.set("empId", empId).save();
			}
		}
		redirect("/bonus");
	}
	
	public void edit() {
		Integer bonusId = getParaToInt("bonus.bonusId");
		Bonus oldBonus = Bonus.me.findById(bonusId);
		Integer oldEmpId = oldBonus.get("empId");
		Bonus bonus = getModel(Bonus.class);
		setBonusTime(bonus);
		String[] empIds = getParaValues("bonus.empId");
		setBonusTime(bonus);
		for (String empId : empIds) {
			if(StrUtil.notBlank(empId)) {
				Integer newEmpId = Integer.parseInt(empId);
				if(oldEmpId == newEmpId) {
					bonus.set("bonusId", bonusId);
					setBonusTime(bonus);
					bonus.update();
				} else {
					bonus.remove("bonusId");
					bonus.put("empId", empId).save();
				}
			}
		}
		redirect("/bonus");
	}
	
	public void delete() {
		Integer bonsId = getParaToInt("bonusId");
		if (Bonus.me.deleteById(bonsId)) {
			renderJson("flag", true);
		} else {
			renderJson("flag", false);
		}
	}
	
	private void setBonusTime(Bonus bonus) {
		String year = getPara("year");
		String month = getPara("month");
		if(StrUtil.notBlank(year) && StrUtil.notBlank(month)) {
			bonus.set("bonusTime", year + "-" + month);
		}
	}
	
	public void bonusInfo() {
		Integer bonusId = getParaToInt("id");
		Map<String, Object> jsonResult = new HashMap<>();
		Bonus bonus = Bonus.me.findById(bonusId);
		if(bonus != null) {
			jsonResult.put("status", "success");
			jsonResult.put("bonus", bonus);
		} else {
			jsonResult.put("status", "fail");
		}
		renderJson("result", jsonResult);
	}
	
}
